﻿using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Hosting;
using EPiServer.Core;
using EPiServer.Shell.WebForms;
using EPiServer.UI;
using EPiServer.Web.Hosting;
using EPiServer.XForms;
using EPiServer.XForms.Util;
using OpenWaves.Web;

[assembly: PublicAssemblyResources("OpenWaves.EPiServer.ImageBrowser.FileSummaryDialogDialog.EditFileSummary.aspx")]
[assembly: PublicAssemblyResources("OpenWaves.EPiServer.ImageBrowser.FileSummaryDialogDialog.EPiServerUI.Master")]
namespace OpenWaves.EPiServer.ImageBrowser.FileSummaryDialogDialog
{
    public partial class EditFileSummary : WebFormsBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        private XFormData _data;

        private UnifiedFile GetSelectedFile()
        {
            var filename = Request["filename"];
            filename = HttpUtility.UrlDecode(filename);
            if (string.IsNullOrEmpty(filename))
            {
                return null;
            }
            var selectedFile = HostingEnvironment.VirtualPathProvider.GetFile(filename) as UnifiedFile;
            return selectedFile;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var selectedFile = this.GetSelectedFile();
            if (selectedFile == null)
            {
                this.lblFileSummaryNotAvailable.Visible = true;
                this.XFormCtrl.Visible = false;
                this.btnInsert.Visible = false;
                return;
            }

            SerializableXmlDocument serializableXmlDocument = new SerializableXmlDocument();
            using (
                Stream inStream =
                    HostingEnvironment.VirtualPathProvider.GetFile(selectedFile.Parent.CustomFileSummaryVirtualPath)
                                      .Open())
                serializableXmlDocument.Load(inStream);
            XForm xform = new XForm();
            xform.Document = serializableXmlDocument;
            this._data = xform.CreateFormData();
            foreach (DictionaryEntry dictionaryEntry in selectedFile.Summary.Dictionary)
            {
                if (dictionaryEntry.Value != null)
                {
                    //try
                    {
                        this._data.SetValue(dictionaryEntry.Key.ToString(), dictionaryEntry.Value.ToString());
                    }
                    //catch (XPathException ex)
                    {
                        //EditCustomFileSummary._log.Error((object)"Error while trying to resolve file summary");
                        //EditCustomFileSummary._log.Error((object)ex.Message);
                    }
                }
            }
            this.XFormCtrl.Data = this._data;
            this.XFormCtrl.FormDefinition = xform;
            //  this.toggleDisplayMenu.DataBind();
        }

        public IContent GetContentForDirectory(UnifiedDirectory directory)
        {
            var content = (IContent)null;
            int pageFolderId;
            if (ReferenceEquals(directory.Provider, VirtualPathHandler.PageFolderProvider) &&
                directory is IContentDirectory &&
                UnifiedDirectory.TryParsePageFolder(directory.VirtualPath, out pageFolderId))
            {
                content = UnifiedDirectory.GetOwnerContentFromVirtualPath(directory.VirtualPath);


                // value.CreateReferenceWithoutVersion() 

                //  if (content == null && !ContentReference.IsNullOrEmpty(this.CurrentFileManager.LoadedContent))
                //      content = DataFactory.Instance.Get<IContent>(this.CurrentFileManager.LoadedContent);
            }
            return content;
        }

        protected void SetContentForAccessControl(UnifiedFile file)
        {
            var contentForDirectory = this.GetContentForDirectory(file.Parent);
            if (contentForDirectory == null)
                return;
            file.SetContentForAccessControl(contentForDirectory.ContentLink);
        }


        protected void OnSave(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            var selectedFile = this.GetSelectedFile();

            var values = this._data.GetValues();
            this.SetContentForAccessControl(selectedFile);
            selectedFile.SaveFileSummary(values);
            // this.BackToPreviousMode();

            ClientScript.RegisterStartupScript(typeof(EditFileSummary), "CloseWindow", "window.onload = function onDialogCloseF() { ToolButtonClick(null); }", true);
        }
    }
}